package com.sunwayworld.dev.config;

import java.util.HashMap;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.sunwayworld.dev.util.StringDevUtil;


public class XmlConfig {

	private VmConfig[] vmConfigs = null;

	private HashMap<String,String> property = new HashMap<String,String>();

	public HashMap getProperty() {
		return property;
	}

	public XmlConfig() {
		this.reloadXml(null);
	}

	public XmlConfig(String filePath) {
		this.reloadXml(filePath);
	}

	public void reloadXml(String filePath) {

		try {
			SAXReader saxReader = new SAXReader();
			if (null == filePath || "".equals(filePath)) {
				filePath = "devtools.xml";
			}
			Document document = saxReader.read(filePath);

			List n_prop = document.selectNodes("//project/property");
			for (int i = 0, n = n_prop.size(); i < n; i++) {
				Element e_prop = (Element) n_prop.get(i);
				Attribute a_prop_name = e_prop.attribute("name");
				Attribute a_prop_value = e_prop.attribute("value");
				property.put(a_prop_name.getText(), a_prop_value.getText());
			}

			List n_vms = document.selectNodes("//project/vm-config/vm");
			vmConfigs = new VmConfig[n_vms.size()];
			String vmpath = StringDevUtil.toString(property.get("vmpath"));
			for (int i = 0, n = n_vms.size(); i < n; i++) {
				Element e_vms = (Element) n_vms.get(i);

				Attribute a_vms = e_vms.attribute("fileName");
				Attribute a_vms2 = e_vms.attribute("package");
				String filePackage = null;
				if (a_vms2 != null) {
					filePackage = a_vms2.getText();
				}
				vmConfigs[i] = new VmConfig(vmpath, e_vms.getText(), a_vms
						.getText(), filePackage);
			}
			//

			document.clearContent();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public VmConfig[] getVmConfigs() {
		return vmConfigs;
	}

	public void setVmConfigs(VmConfig[] vmConfigs) {
		this.vmConfigs = vmConfigs;
	}
}
